package com.chuanyang.driverh.mainorder;


import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.PoiOverlay;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.amap.MapUtils;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.responseresult.CurrentGpsData;
import com.chuanyang.driverh.responseresult.CurrentGpsResult;
import com.chuanyang.driverh.responseresult.LookWaybillData;
import com.chuanyang.driverh.responseresult.LookWaybillResult;
import com.chuanyang.driverh.utils.BitmapUtil;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshDelieryEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class OrderLocationActivity extends BaseTitleActivity {
    private MapView mMapView = null;
    private AMap aMap;
    private PoiOverlay polyline;
    private LinearLayout ll_first_car_msg;
    private RelativeLayout rl_rotation_arrow;
    private ImageView iv_rotation_arrow;
    private String orderId = "";
    private String orderNo = "";

    private List<LookWaybillData.DataBean> wayBillEntityList = new ArrayList<>();

    private ImageView iv_driver_photo_pop;
    private TextView tv_driver_name_pop;
    private TextView tv_driver_phone_pop;
    private TextView rb_driver_car_number;
    private TextView tv_driver_waybill_number;
    private TextView tv_fleet;
    private TextView tv_goods;
    private TextView tv_yundan_xiangqing;

    private UiSettings mUiSettings;//定义一个UiSettings对象

    private ArrayList<MarkerOptions> markerGuideList = new ArrayList<>();
    private ArrayList<CurrentGpsData> billEntityList = new ArrayList<>();


    private MarkerOptions markerOptionsGuide;
    private LatLng guide;
    private LinearLayout ll_order_msg, ll_photo;
    private int k = 0;
    private TextView tv_waybill_time;
    private ImageView iv_driver_car_pop;
    private CurrentGpsData currentPosition;
    private LookWaybillData lookWaybillData;
    private LinearLayout rl_driver_msg;
    private int status;
    private boolean isReflesh;

    @Override
    protected int getContentResId() {
        return R.layout.order_act_location;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMapView = (MapView) findViewById(R.id.map_order);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        //初始化地图变量
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setBackImg();
        getTitleTextView().setText("查看运单");
        getRightTextView().setText("运单列表");
        if (!TextUtils.isEmpty(getIntent().getStringExtra("orderId"))) {
            orderId = getIntent().getStringExtra("orderId");
        }
        ll_first_car_msg = (LinearLayout) findViewById(R.id.ll_first_car_msg);
        rl_rotation_arrow = (RelativeLayout) findViewById(R.id.rl_rotation_arrow);
        iv_rotation_arrow = (ImageView) findViewById(R.id.iv_rotation_arrow);
        iv_rotation_arrow.setOnClickListener(this);
        iv_driver_photo_pop = (ImageView) findViewById(R.id.iv_driver_photo_pop);
        iv_driver_car_pop = (ImageView) findViewById(R.id.iv_driver_car_pop);
        tv_driver_name_pop = (TextView) findViewById(R.id.tv_driver_name_pop);
        tv_driver_phone_pop = (TextView) findViewById(R.id.tv_driver_phone_pop);
        rb_driver_car_number = (TextView) findViewById(R.id.rb_driver_car_number);
        tv_driver_waybill_number = (TextView) findViewById(R.id.tv_driver_waybill_number);
        tv_yundan_xiangqing = (TextView) findViewById(R.id.tv_yundan_xiangqing);
        tv_waybill_time = (TextView) findViewById(R.id.tv_waybill_time);
        tv_fleet = (TextView) findViewById(R.id.tv_fleet);
        tv_goods = (TextView) findViewById(R.id.tv_goods);

        ll_order_msg = (LinearLayout) findViewById(R.id.ll_order_msg);
        rl_driver_msg = (LinearLayout) findViewById(R.id.rl_driver_msg);
        ll_order_msg.setOnClickListener(this);
        ll_photo = (LinearLayout) findViewById(R.id.ll_photo);
        ll_photo.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(getIntent().getStringExtra("orderId"))) {
            orderId = getIntent().getStringExtra("orderId");
            if (!TextUtils.isEmpty(getIntent().getStringExtra("orderNo"))) {
                orderNo = getIntent().getStringExtra("orderNo");
                getWybill(orderId, orderNo, "1", "200");//之后要有分页
                // getWybill("91", "D01121400000013", "1", "2");//之后要有分页
                GetCarCurrentStatusByOrderId(orderId);
                // GetCarCurrentStatusByOrderId("91");
            }
        }

    }

    @Override
    protected void initListener() {

    }



    private void setUpMap() {
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类
        mUiSettings.setScaleControlsEnabled(true);//显示比例尺控件
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        //myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        //myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);

    }

    @Override
    protected void baseGoEnsure() {
        if (wayBillEntityList.size() > 0) {
            Intent intent = new Intent(OrderLocationActivity.this, OrderDriverListActivity.class);
            lookWaybillData.setData(wayBillEntityList);
            intent.putExtra("lookWaybillData", lookWaybillData);
            intent.putExtra("type",1);
            //  intent.putExtra("orderNo", orderNo);
            startActivityForResult(intent, 1);
        }
        else {
            PrintUtil.toast(activityContext,"该订单没有分配运单！");
        }
    }
    public void onEventMainThread(RefleshDelieryEvent event) {
        if (event.isReflesh()) {
            if(!TextUtils.isEmpty(orderNo)&&!TextUtils.isEmpty(orderId))
            {
                isReflesh = true;
                getWybill(orderId, orderNo, "1", "200");//之后要有分页

            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode)
        {
            case 1:
                rl_driver_msg.setVisibility(View.VISIBLE);
                LookWaybillData.DataBean  bean= (LookWaybillData.DataBean) data.getSerializableExtra("data");
                for(int i=0;i<wayBillEntityList.size();i++)
                {
                    if(wayBillEntityList.get(i).getWaybillId()==bean.getWaybillId())
                    {
                        k=i;
                    }
                }
                //  k = Integer.parseInt(data.getStringExtra("position"));
                // LookWaybillData.DataBean bean = wayBillEntityList.get(k);
                fillView(bean);
                if (aMap != null && billEntityList.size() > 0) {
                    aMap.clear();
                    currentPosition=null;
                    showMark(bean);
                }
                break;
            case 2:
                int position=data.getIntExtra("position",-1);
                if(position!=-1)
                {
                    wayBillEntityList.remove(position);
                    rl_driver_msg.setVisibility(View.GONE);
                    if (aMap != null) {
                        aMap.clear();
                    }
                }

                break;
        }
    }

    private void showMark(LookWaybillData.DataBean dataBean) {
        //MapUtils.getGdLatLng转换为高德地图坐标
        for (int i = 0; i < billEntityList.size(); i++)
        {
//                if (billEntityList.get(i).getCarMark().equals(dataBean.getPlateNumber())) {
                if (billEntityList.get(i).getPlateNumber().equals(dataBean.getPlateNumber())) {
                    currentPosition = billEntityList.get(i);
                }
        }
        if(currentPosition!=null) {
            guide = MapUtils.getGdLatLng(OrderLocationActivity.this, new LatLng(Float.parseFloat(currentPosition.getLast_lat()),
                    Float.parseFloat(currentPosition.getLast_lon())));
            markerOptionsGuide = new MarkerOptions();
            //  markerOptionsGuide.position(guide).title(billEntityList.get(i).getCarMark());
            markerOptionsGuide.position(guide);
//                        markerOptionsGuide.title(billEntityList.get(i).getFirmName());
//                        markerOptionsGuide.snippet(billEntityList.get(i).getAddress());
            markerOptionsGuide.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                    .decodeResource(getResources(), R.mipmap.location)));
            markerOptionsGuide.title(currentPosition.getCarMark()+"");
//        markerGuideList.add(markerOptionsGuide);
            markerOptionsGuide.title(dataBean.getPlateNumber());
            aMap.addMarker(markerOptionsGuide);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(guide));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_rotation_arrow:
                //判断ll_first_car_msg是隐藏还是显示；
                if (ll_first_car_msg.getVisibility() == View.GONE) {
                    ll_first_car_msg.setVisibility(View.VISIBLE);
                    iv_rotation_arrow.setRotation(90);
                } else if (ll_first_car_msg.getVisibility() == View.VISIBLE) {
                    ll_first_car_msg.setVisibility(View.GONE);
                    iv_rotation_arrow.setRotation(-90);
                }
                break;
            case R.id.ll_order_msg:
                if (wayBillEntityList.size() > 0) {
                    if (!TextUtils.isEmpty("" + wayBillEntityList.get(k).getDriverId())) {
                        Intent intent = new Intent(OrderLocationActivity.this, LookWaybillDetailActivity.class);
                        intent.putExtra("LookWaybill", wayBillEntityList.get(k));
                        intent.putExtra("position",k);
                        startActivityForResult(intent,2);
                    }
                }
                break;


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }



    //根据订单ID查看运单
    private void getWybill(String orderId, String orderNo, String page, String length) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("orderId", orderId);
        params.put("orderNo", orderNo);
        params.put("page", page);
        params.put("length", length);
        MyHttpUtil.selectByOrderId(activityContext,params, new MyCallback<LookWaybillResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(LookWaybillResult result, int id) {
                if (result.getCode() == ConstUtil.OK)
                {
                    lookWaybillData = result.getData();
                    wayBillEntityList.addAll(result.getData().getData());
                    if(!isReflesh) {
                        fillView(wayBillEntityList.get(0));
                    }
                } else {
                    PrintUtil.toast(activityContext,result.getMsg());
                    rl_driver_msg.setVisibility(View.GONE);
                }
            }
        });
    }

    private void fillView(LookWaybillData.DataBean dataBean) {
        tv_driver_name_pop.setText(dataBean.getDriverName());
        tv_driver_phone_pop.setText(dataBean.getPhone());
        BitmapUtil.showImgForNetPath( dataBean.getUserImage(),iv_driver_photo_pop);
        if (dataBean.getFleetType()!=null && dataBean.getFleetType().equals("2")) {
            iv_driver_car_pop.setImageResource(R.mipmap.car_transport);

        } else {
            iv_driver_car_pop.setImageResource(R.mipmap.ship_translate);

        }
        tv_fleet.setText("所属队伍：" + dataBean.getFleetName());
        tv_driver_waybill_number.setText("运单号：" + dataBean.getWaybillNo());
        tv_goods.setText("货品：" + dataBean.getGoodsName());
        rb_driver_car_number.setText(dataBean.getPlateNumber());
        tv_waybill_time.setText(dataBean.getCreatetime());
        try {
            status = dataBean.getWaybillStatus();
        } catch (Exception e) {
            status = -1;
        }
        if (status < 0) {
            tv_yundan_xiangqing.setText("运单异常");
        } else if (dataBean.getWaybillStatus()==0) {
            tv_yundan_xiangqing.setText("初始化");

        } else if (dataBean.getWaybillStatus()==2) {
            tv_yundan_xiangqing.setText("待装货");

        } else if (dataBean.getWaybillStatus()==3) {
            tv_yundan_xiangqing.setText("装货中");

        } else if (dataBean.getWaybillStatus()==4) {
            tv_yundan_xiangqing.setText("运输中");

        } else if (dataBean.getWaybillStatus()==5) {
            tv_yundan_xiangqing.setText("卸货中");

        } else if (dataBean.getWaybillStatus()==6) {
            tv_yundan_xiangqing.setText("待确认收货");

        } else if (dataBean.getWaybillStatus()==7) {
            tv_yundan_xiangqing.setText("已完成");


        }
    }


    /**
     * 获取车辆的所有的GPS定位，
     *
     * @param orderId
     */
    private void GetCarCurrentStatusByOrderId(String orderId) {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("orderId", orderId);
        MyHttpUtil.GetCarCurrentStatusByOrderId(activityContext,params, new MyCallback<CurrentGpsResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(CurrentGpsResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                        billEntityList.addAll(result.getData());
                        //设置标记点
                        aMap.clear();
                        for (int i = 0; i < billEntityList.size(); i++) {
                            //MapUtils.getGdLatLng转换为高德地图坐标
                            guide = MapUtils.getGdLatLng(OrderLocationActivity.this, new LatLng(Float.parseFloat(billEntityList.get(i).getLast_lat()),
                                    Float.parseFloat(billEntityList.get(i).getLast_lon())));
                            markerOptionsGuide = new MarkerOptions();
                            //  markerOptionsGuide.position(guide).title(billEntityList.get(i).getCarMark());
                            markerOptionsGuide.position(guide);
        //                        markerOptionsGuide.title(billEntityList.get(i).getFirmName());
        //                        markerOptionsGuide.snippet(billEntityList.get(i).getAddress());
                            markerOptionsGuide.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                                    .decodeResource(getResources(), R.mipmap.location)));
                            markerOptionsGuide.title(billEntityList.get(i).getCarMark()+"");
                            markerGuideList.add(markerOptionsGuide);
                        }
                        aMap.addMarkers(markerGuideList, true);
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });
    }
}
